package com.book.modules.configure;

import com.book.common.api.entity.CurrentUser;
import com.book.common.api.oauth.HystrixConstant;
import com.book.modules.helper.CurrentUserHelper;
import com.book.modules.util.HttpContextUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Description： 服务间调用feign传递header中的token 拦截器
 *
 * @Author： leo.xiong
 * @CreateDate： 2019/10/15 11:54
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
@Component
public class FeignRequestInterceptorConfig implements RequestInterceptor {
    @Autowired
    private CurrentUserHelper currentUserHelper;

    /**
     * 获取token信息
     * 1、header传入
     * 2、bookToken参数传入
     * 3、当前用户的token
     * 如果存在，则在header中存储一份数据 key：Authorization，value前面加上Bearer，spring cloud oauth2就可以获取token信息
     *
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        if (request != null) {
            Enumeration<String> headerNames = request.getHeaderNames();
            Boolean flag = true;
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String value = request.getHeader(name);
                    if (StringUtils.isEmpty(value)) {
                        continue;
                    }
                    if (HystrixConstant.AUTHORIZATION.equalsIgnoreCase(name)) {
                        if (HystrixConstant.BEARER.equalsIgnoreCase(value)) {
                            continue;
                        }
                        requestTemplate.header(HystrixConstant.AUTHORIZATION, HystrixConstant.BEARER + value);
                        flag = false;
                    } else {
                        requestTemplate.header(name, value);
                    }
                }
            }
            if (flag) {
                String token = request.getParameter(HystrixConstant.BOOK_TOKEN);
                if (StringUtils.isNotEmpty(token)) {
                    requestTemplate.header(HystrixConstant.AUTHORIZATION, HystrixConstant.BEARER + token);
                    flag = false;
                }
            }
            if (flag) {
                CurrentUser currentUser = currentUserHelper.getCurrentUser();
                if (currentUser != null && StringUtils.isNotEmpty(currentUser.getToken())) {
                    requestTemplate.header(HystrixConstant.AUTHORIZATION, HystrixConstant.BEARER + currentUser.getToken());
                }
            }
        }
    }

}
